package com.cxs.shopstore.controllers;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cxs.shopstore.config.ImgCodeConf;
import com.cxs.shopstore.config.JwtPropertiesConfig;
import com.cxs.shopstore.config.RedisTokenConf;
import com.cxs.shopstore.models.User;
import com.cxs.shopstore.security.token.JwtUtils;
import com.cxs.shopstore.security.token.RsaUtils;
import com.cxs.shopstore.service.UserService;
import com.cxs.shopstore.utils.ImgUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cxs
 * @since 2021-05-06
 */
@Slf4j
@RestController
@RequestMapping("/user")
@SuppressWarnings("all")
public class UserController {
    @Autowired
    private UserService service;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private ImgUtils imgUtils;
    @Autowired
    private JwtPropertiesConfig jwtPropertiesConfig;
    @Autowired
    private RedisTokenConf redisTokenConf;
    @Autowired
    private ImgCodeConf imgCodeConf;

    /**
     * 用户登录逻辑
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Map<String,Object> login(HttpServletRequest request, User user){
        String token = null ;
        Map<String,Object> map = new HashMap<>();
        if(user != null && user.getImgKey() != null && user.getImgKey() != ""){
            String key = user.getImgKey();
            //查询redis验证码是否正确
            String redisImgCode = (String) redisTemplate.opsForValue().get(imgCodeConf.getPrifex() + key);
            if(user.getCode() != null && user.getCode() != ""){
                if(user.getCode().toUpperCase(Locale.ROOT).equals(redisImgCode)){
                    log.info("code check success! "+"redis:"+redisImgCode+"== input:"+ user.getCode().toUpperCase(Locale.ROOT));
                    QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("user_name",user.getUserName()).eq("user_password",user.getUserPassword());
                    User userobj = service.getOne(wrapper);
                    if(userobj != null){
                        //token生成
                        try {
                            token = JwtUtils.generateToken(
                                    new com.cxs.shopstore.security.token.User(userobj.getUserId(),userobj.getUserName()),
                                    RsaUtils.getPrivateKey(jwtPropertiesConfig.getPriKeyPath()),
                                    jwtPropertiesConfig.getExpire());
                            //存放redis
                            redisTemplate.opsForValue().set(redisTokenConf.getPrefex() + userobj.getUserId(),token);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //用户头像base64处理
                        imgUtils.imgPathToBase64String(userobj);
                        if(userobj.getUserIsAdmin() == 1){
                            //是管理员
                            map.put("code",200);
                            map.put("view","admin.html");
                            map.put("primarykey","admin");
                            map.put("msg","登录成功");
                            map.put("data",userobj);
                            map.put("token",token);
                        }else{
                            //普通用户
                            map.put("code",200);
                            map.put("view","index.html");
                            map.put("msg","登录成功");
                            map.put("primarykey","user");
                            map.put("data",userobj);
                            map.put("token",token);
                        }
                    }else{
                        map.put("code",401);
                        map.put("msg","用户名或密码错误");
                    }
                }else{
                    log.error("user.getCode().toUpperCase(Locale.ROOT) != redisImgCode");
                    map.put("code",500);
                    map.put("msg","验证码校验失败!");
                }
            }else{
                log.error("user.getCode() = null || user.getCode() = \"\"");
                map.put("code",500);
                map.put("msg","验证码不能为空!");
            }
        }
        return map;
    }

    /**
     * 用户信息的修改
     * @param user
     * @return
     */
    @PostMapping("/updatebyId")
    public Map<String,Object> updatebyId(User user){
        Map<String,Object> map = new HashMap<>();
        if(service.updateById(user)){
            map.put("status",true);
            map.put("msg","修改成功");
            map.put("data",imgUtils.imgPathToBase64String(service.getById(user.getUserId())));
        }else{
            map.put("status",false);
            map.put("msg","修改失败");
        }
        return map;
    }
}

